<?php

namespace app\admin\controller\qingdongwms;


use addons\qingdongwms\model\Achievement;
use addons\qingdongwms\model\Business;
use addons\qingdongwms\model\Contacts;
use addons\qingdongwms\model\Event;
use addons\qingdongwms\model\FormField;
use addons\qingdongwms\model\ReceivablesPlan;
use addons\qingdongwms\model\Staff;
use app\admin\controller\qingdongwms\Base;
use addons\qingdongwms\model\Contract;
use addons\qingdongwms\model\Customer;
use addons\qingdongwms\model\Field;
use addons\qingdongwms\model\Receivables;
use addons\qingdongwms\model\Record;
use addons\qingdongwms\model\Leads;
use addons\qingdongwms\model\ExamineRecord;

use app\admin\controller\qingdongwms\general\Ratio;
use think\Config;

/**
 * 控制台
 * @icon fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Base {

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查看
     */
    public function index() {

        $times=input('times','thismonth');
        $type=input('type',2);
        if ($type == 1) {//我的
            $whereStaff['staff_id'] = $this->auth->id;
            $active='second';
        } elseif ($type == 2) {//本人及下属
            $whereStaff['staff_id'] = ['in', Staff::getMyStaffIds()];
            $active='first';
        } elseif ($type == 3) {//仅下属
            $whereStaff['staff_id'] = ['in', Staff::getLowerStaffId()];
            $active='third';
        }else{
            $this->error('参数错误');
        }
        $where1=[
            'createtime'=>['between',setTimes($times,'time')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        //新增客户
        $addCustomer=Customer::where($where1)->count();
        //新增联系人
        $addContacts=Contacts::where($where1)->count();
        //新增商机
        $addBusiness=Business::where($where1)->count();
        //商机金额
        $businessMoney=Business::where($where1)->sum('money');
        //新建跟进记录
        $addRecord=Record::where(['relation_type' => 1,'follow_type'=>['neq','其它'],'createtime'=>$where1['createtime'],'create_staff_id'=>$where1['owner_staff_id']])->count();

        $where2=[
            'order_date'=>['between',setTimes($times,'datetime')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        //新增合同
        $addContract=Contract::where($where2)->where(['check_status'=>2])->count();
        //合同金额
        $contractMoney=Contract::where($where2)->where(['check_status'=>2])->sum('money');

        $where3=[
            'return_time'=>['between',setTimes($times,'date')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        //回款金额
        $receivablesMoney=Receivables::where($where3)->where(['check_status'=>2])->sum('money');
        $briefing=[
            'addCustomer'=>$addCustomer,
            'addContacts'=>$addContacts,
            'addBusiness'=>$addBusiness,
            'addContract'=>$addContract,
            'contractMoney'=>$contractMoney,
            'businessMoney'=>$businessMoney,
            'receivablesMoney'=>$receivablesMoney,
            'addRecord'=>$addRecord,
        ];

        if(!in_array($times,['tomorrow','nextweek','nextmonth','nextquarter','nextyear'])){//未来事件不比较数据
//数据比较
            if(in_array($times,['today','yesterday'])){//日
                if($times == 'today'){
                    $ratio_text='较昨天';
                }else{
                    $ratio_text='较前天';
                }
                $start = $where1['createtime'][1][0];
                $end = $where1['createtime'][1][1];
                $where1['createtime'] = ['between', [strtotime('-1 day', $start), strtotime('-1 day', $end)]];
                $start = strtotime($where2['order_date'][1][0]);
                $end = strtotime($where2['order_date'][1][1]);
                $where2['order_date'] = ['between', [
                    date('Y-m-d H:i:s', strtotime('-1 day', $start)),
                    date('Y-m-d H:i:s', strtotime('-1 day', $end))]];
                $start = strtotime($where3['return_time'][1][0]);
                $end = strtotime($where3['return_time'][1][1]);
                $where3['return_time'] = ['between', [
                    date('Y-m-d', strtotime('-1 day', $start)),
                    date('Y-m-d', strtotime('-1 day', $end))]];

            }else if(in_array($times,['thisweek','lastweek'])){//周
                if($times == 'thisweek'){
                    $ratio_text='较上周';
                }else{
                    $ratio_text='较上上周';
                }
                $start = $where1['createtime'][1][0];
                $end = $where1['createtime'][1][1];
                $where1['createtime'] = ['between', [strtotime('-1 week', $start), strtotime('-1 week', $end)]];
                $start = strtotime($where2['order_date'][1][0]);
                $end = strtotime($where2['order_date'][1][1]);
                $where2['order_date'] = ['between', [
                    date('Y-m-d H:i:s', strtotime('-1 week', $start)),
                    date('Y-m-d H:i:s', strtotime('-1 week', $end))]];
                $start = strtotime($where3['return_time'][1][0]);
                $end = strtotime($where3['return_time'][1][1]);
                $where3['return_time'] = ['between', [
                    date('Y-m-d', strtotime('-1 week', $start)),
                    date('Y-m-d', strtotime('-1 week', $end))]];

            }else if(in_array($times,['thismonth','lastmonth',])){//月
                if($times == 'thismonth'){
                    $ratio_text='较上月';
                }else{
                    $ratio_text='较上上月';
                }
                $start = $where1['createtime'][1][0];
                $end = $where1['createtime'][1][1];
                $where1['createtime'] = ['between', [strtotime('-1 month', $start), strtotime('-1 month', $end)]];
                $start = strtotime($where2['order_date'][1][0]);
                $end = strtotime($where2['order_date'][1][1]);
                $where2['order_date'] = ['between', [
                    date('Y-m-d H:i:s', strtotime('-1 month', $start)),
                    date('Y-m-d H:i:s', strtotime('-1 month', $end))]];
                $start = strtotime($where3['return_time'][1][0]);
                $end = strtotime($where3['return_time'][1][1]);
                $where3['return_time'] = ['between', [
                    date('Y-m-d', strtotime('-1 month', $start)),
                    date('Y-m-d', strtotime('-1 month', $end))]];

            }else if(in_array($times,['thisquarter','lastquarter'])){//季度
                if($times == 'thisquarter'){
                    $ratio_text='较上季度';
                }else{
                    $ratio_text='较上上季度';
                }
                $start = $where1['createtime'][1][0];
                $end = $where1['createtime'][1][1];
                $where1['createtime'] = ['between', [strtotime('-3 month', $start), strtotime('-3 month', $end)]];
                $start = strtotime($where2['order_date'][1][0]);
                $end = strtotime($where2['order_date'][1][1]);
                $where2['order_date'] = ['between', [
                    date('Y-m-d H:i:s', strtotime('-3 month', $start)),
                    date('Y-m-d H:i:s', strtotime('-3 month', $end))]];
                $start = strtotime($where3['return_time'][1][0]);
                $end = strtotime($where3['return_time'][1][1]);
                $where3['return_time'] = ['between', [
                    date('Y-m-d', strtotime('-3 month', $start)),
                    date('Y-m-d', strtotime('-3 month', $end))]];

            }else if(in_array($times,['thisyear','lastyear'])){//年
                if($times == 'thisyear'){
                    $ratio_text='较去年';
                }else{
                    $ratio_text='较前年';
                }
                $start = $where1['createtime'][1][0];
                $end = $where1['createtime'][1][1];
                $where1['createtime'] = ['between', [strtotime('-1 year', $start), strtotime('-1 year', $end)]];
                $start = strtotime($where2['order_date'][1][0]);
                $end = strtotime($where2['order_date'][1][1]);
                $where2['order_date'] = ['between', [
                    date('Y-m-d H:i:s', strtotime('-1 year', $start)),
                    date('Y-m-d H:i:s', strtotime('-1 year', $end))]];
                $start = strtotime($where3['return_time'][1][0]);
                $end = strtotime($where3['return_time'][1][1]);
                $where3['return_time'] = ['between', [
                    date('Y-m-d', strtotime('-1 year', $start)),
                    date('Y-m-d', strtotime('-1 year', $end))]];
            }else{
                $ratio_text='';
            }
            //新增客户
            $last_addCustomer=Customer::where($where1)->count();
            //新增联系人
            $last_addContacts=Contacts::where($where1)->count();
            //新增商机
            $last_addBusiness=Business::where($where1)->count();
            //商机金额
            $last_businessMoney=Business::where($where1)->sum('money');
            //新建跟进记录
            $last_addRecord=Record::where(['relation_type' => 1,'follow_type'=>['neq','其它'],'createtime'=>$where1['createtime'],'create_staff_id'=>$where1['owner_staff_id']])->count();
            //新增合同
            $last_addContract=Contract::where($where2)->where(['check_status'=>2])->count();
            //合同金额
            $last_contractMoney=Contract::where($where2)->where(['check_status'=>2])->sum('money');
            //回款金额
            $last_receivablesMoney = Receivables::where($where3)->where(['check_status'=>2])->sum('money');
            $briefing['ratio_text']=$ratio_text;
            $briefing['customer_ratio'] = $this->getRatio($addCustomer, $last_addCustomer);
            $briefing['contacts_ratio'] = $this->getRatio($addContacts, $last_addContacts);
            $briefing['business_ratio'] = $this->getRatio($addBusiness, $last_addBusiness);
            $briefing['business_money_ratio'] = $this->getRatio($businessMoney, $last_businessMoney);
            $briefing['record_ratio'] = $this->getRatio($addRecord, $last_addRecord);
            $briefing['contract_ratio'] = $this->getRatio($addContract, $last_addContract);
            $briefing['contract_money_ratio'] = $this->getRatio($contractMoney, $last_contractMoney);
            $briefing['receivables_money_ratio'] = $this->getRatio($receivablesMoney, $last_receivablesMoney);
        }


        //6个月内的曲线
        $month6 = date('Y-m-d', strtotime('-6 month')). ',' . date('Y-m-d') ;
        $where4 = [
            'createtime' => ['between', setTimes($month6, 'time')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $customer6=Customer::where($where4)
            ->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();

        $contacts6=Contacts::where($where4)
            ->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();

        $business6=Business::where($where4)
            ->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();

        $businessmoney6=Business::where($where4)
            ->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,sum(money) as c")->group('ctime')->select();

        $record6=Record::where(['relation_type' => 1,'follow_type'=>['neq','其它'],'createtime'=>$where1['createtime'],'create_staff_id'=>$where4['owner_staff_id']])
            ->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();
        $where5 = [
            'order_date' => ['between', setTimes($month6, 'datetime')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];

        //新增合同
        $contract6 = Contract::where($where5)->where(['check_status'=>2])->field("FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();;
        //合同金额
        $contractMoney6 = Contract::where($where5)->where(['check_status'=>2])->field("FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),'%Y-%m') as ctime,sum(money) as c")->group('ctime')->select();;

        $where6 = [
            'return_time' => ['between', setTimes($month6, 'date')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        //回款金额
        $receivablesMoney=Receivables::where($where6)->where(['check_status'=>2])->field("FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),'%Y-%m') as ctime,sum(money) as c")->group('ctime')->select();;
        $this->view->assign([
            'briefing' => $briefing,
            'type' => $type,
            'times' => $times,
            'active' => $active,
            'dates' => input('dates'),
            'wheredate' =>implode(' - ',setTimes($times,'date')),
            'wheredatetime' => implode(' - ',setTimes($times,'datetime')),

        ]);
        $d=setTimes($month6, 'date');
        $echarts=[
            'customer'=>$this->getValues($d,$customer6),
            'contacts'=>$this->getValues($d,$contacts6),
            'contract'=>$this->getValues($d,$contract6),
            'business'=>$this->getValues($d,$business6),
            'business_money'=>$this->getValues($d,$businessmoney6),
            'record'=>$this->getValues($d,$record6),
            'contract_money'=>$this->getValues($d,$contractMoney6),
            'receivables_money'=>$this->getValues($d,$receivablesMoney),
        ];

        $year1=date('Y-m-d H:i:s',strtotime('-1 year'));
        $month6=date('Y-m-d H:i:s',strtotime('-6 month'));
        $month3=date('Y-m-d H:i:s',strtotime('-3 month'));
        $day30=date('Y-m-d H:i:s',strtotime('-30 day'));
        $day15=date('Y-m-d H:i:s',strtotime('-15 day'));
        $day7=date('Y-m-d H:i:s',strtotime('-7 day'));
        $where7day=[
            'last_time'=>['between',[$day15,$day7]],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $where15day=[
            'last_time'=>['between',[$day30,$day15]],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $where30day=[
            'last_time'=>['between',[$month3,$day30]],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $where3month=[
            'last_time'=>['between',[$month6,$month3]],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $where6month=[
            'last_time'=>['between',[$year1,$month6]],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $over=[
            'next_time'=>['between',[$year1,date('Y-m-d H:i:s')]],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $day7count = Customer::where($where7day)->count();
        $day15count = Customer::where($where15day)->count();
        $day30count = Customer::where($where30day)->count();
        $month3count = Customer::where($where3month)->count();
        $month6count = Customer::where($where6month)->count();
        $overcount = Customer::where($over)->count();
        $this->view->assign('nocontacts', [
            'day7count' => $day7count,
            'day15count' => $day15count,
            'day30count' => $day30count,
            'month3count' => $month3count,
            'month6count' => $month6count,
            'overcount' => $overcount,
            'where7day' => implode(' - ', $where7day['last_time'][1]),
            'where15day' => implode(' - ', $where15day['last_time'][1]),
            'where30day' => implode(' - ', $where30day['last_time'][1]),
            'where3month' => implode(' - ', $where3month['last_time'][1]),
            'where6month' => implode(' - ', $where6month['last_time'][1]),
            'over' => implode(' - ', $over['next_time'][1]),
        ]);
        $this->view->assign('summary',$this->getCustomer());

        $this->assignconfig('echarts',$echarts);
        return $this->view->fetch();
    }
    /**
     * 业绩指标完成率
     */
    public function get_achievement_detail()
    {
        $times = input('times','thismonth');
        $status = input('status', 3);//3合同 4回款
        $type = input('type', 3);//1仅本人 2团队 3仅下属
        if ($type == 1) {//我的
            $staff_id = $this->auth->id;
        } elseif ($type == 2) {//本人及下属
            $staff_id = ['in', Staff::getMyStaffIds()];
        } elseif ($type == 3) {//仅下属
            $staff_id = ['in', Staff::getLowerStaffId()];
        }else{
            $this->error('参数错误');
        }
        $times=setTimes($times,'date');
        $years=getYearByTime(strtotime($times[0]),strtotime($times[1]));
        $model = new Achievement();
        $achievement = $model->where([
            'obj_id' => $this->auth->id,
            'type' => 3,
            'year' => ['in',$years],
            'status' => $status
        ])->select();

        $achievementMoney = 0.00;
        //获取需要查询的月份
        $month = getmonthByTime(strtotime($times[0]), strtotime($times[1]));
        foreach ($achievement as $k=>$v) {
            foreach ($month as $key=>$val) {
                if ($v['year'] == $key) {
                    foreach ($val as $key1=>$val1) {
                        $achievementMoney += $v[Achievement::getMonthField($v['year'].'-'.$val1)];
                    }
                }
            }
        }
        $where['order_date'] = ['between', $times];
        $where['check_status'] = 2;
        $where['owner_staff_id'] = $staff_id;
        $contractMoney = Contract::where([
            'order_date'=>['between', $times],
            'check_status'=>2,
            'owner_staff_id'=>$staff_id,
        ])->sum('money');

        $receivablesMoney = Receivables::where([
            'return_time'=>['between', $times],
            'check_status'=>2,
            'owner_staff_id'=>$staff_id,
        ])->sum('money');

        $data = [];
        $data['contractMoney'] = $contractMoney ? : '0.00';
        $data['receivablesMoney'] = $receivablesMoney ? : '0.00';
        $data['achievementMoney'] = $achievementMoney ? : '0.00';
        //完成率
        $rate = 0.00;
        if ($status == 1) {
            $rate = $achievementMoney ? round(($contractMoney/$achievementMoney),4) : 0.00;
        } else {
            $rate = $achievementMoney ? round(($receivablesMoney/$achievementMoney),4) : 0.00;
        }
        $data['rate'] = $rate *100;
        $this->success('请求成功','', $data);
    }

    /**
     * 合同金额目标及完成情况
     */
    public function get_achievement()
    {
        $times = input('times','thismonth');
        $status = input('status', 3);//3合同 4回款
        $type = input('type', 2);//1仅本人 2团队 3仅下属
        if ($type == 1) {//我的
            $staff_id = $this->auth->id;
        } elseif ($type == 2) {//本人及下属
            $staff_id = ['in', Staff::getMyStaffIds()];
        } elseif ($type == 3) {//仅下属
            $staff_id = ['in', Staff::getLowerStaffId()];
        }else{
            $this->error('参数错误');
        }
        $dates=setTimes($times,'date');
        $years=getYearByTime(strtotime($dates[0]),strtotime($dates[1]));

        $model = new Achievement();
        $achievement = $model->where([
            'obj_id' => $this->auth->id,
            'type' => 3,
            'year' => ['in',$years],
            'status' => $status
        ])->select();
        $achievement=collection($achievement)->toArray();
        if (in_array($times, ['thisquarter', 'lastquarter', 'nextquarter'])) {//季度
            if($status == 3){
                $where['order_date'] = ['between', [$years[0] . '-01-01', ($years[0] + 1). '-12-31']];
                $where['check_status'] = 2;
                $where['owner_staff_id'] = $staff_id;
                $moneys = Contract::where($where)->group('month')
                    ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),"%Y-%m") as month')
                    ->select();
            }else{
                $where2['return_time'] = ['between', [$years[0] . '-01-01', ($years[0] + 1) . '-12-31']];
                $where2['check_status'] = 2;
                $where2['owner_staff_id'] = $staff_id;
                $moneys = Receivables::where($where2)->group('month')
                    ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),"%Y-%m") as month')
                    ->select();
            }
            $list=[];
            foreach ($moneys as $v){
                $list[$v['month']]=$v['number'];
            }
            $achievementMoney=[];
            foreach ($achievement as $k=>$v) {
                foreach ($v as $field => $val) {
                    $achievementMoney[$v['year'] .'-'. Achievement::getFieldMonth($field)]=$val;
                }
            }
            $result=['times'=>[],'achievement'=>[],'money'=>[]];
            $startTime=strtotime($years[0] . '-01-01');
            for($i=1;$i<=8;$i++){
                $m=$i*2;
                $result['times'][]=[
                    date('Y-m',strtotime("+".($m-2)." month",$startTime)),
                    date('Y-m',strtotime("+".($m-1)." month",$startTime)),
                    date('Y-m',strtotime("+".$m." month",$startTime)),
                ];
            }
            foreach ($result['times'] as $k=>$t){
                $a=0;$l=0;
                foreach ($t as $t1) {
                    $a += $achievementMoney[$t1] ?? 0;
                    $l += $list[$t1] ?? 0;
                }
                $result['times'][$k]=implode(',',$t);
                $result['achievement'][]=$a;
                $result['money'][]=$l;
            }

        } else if (in_array($times, ['thisyear', 'lastyear', 'nextyear'])) {//年
            if($status == 3){
                $where['order_date'] = ['between', [($years[0] - 2) . '-01-01', ($years[0] + 2) . '-12-31']];
                $where['check_status'] = 2;
                $where['owner_staff_id'] = $staff_id;
                $moneys = Contract::where($where)->group('month')
                    ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),"%Y") as month')
                    ->select();
            }else{
                $where2['return_time'] = ['between', [($years[0] - 2) . '-01-01', ($years[0] + 2) . '-12-31']];
                $where2['check_status'] = 2;
                $where2['owner_staff_id'] = $staff_id;
                $moneys = Receivables::where($where2)->group('month')
                    ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),"%Y") as month')
                    ->select();
            }
            $list=[];
            foreach ($moneys as $v){
                $list[$v['month']]=$v['number'];
            }
            $achievementMoney=[];
            foreach ($achievement as $k=>$v) {
                foreach ($v as $field => $val) {
                    $achievementMoney[$v['year']]=$val;
                }
            }
            $result=['times'=>[],'achievement'=>[],'money'=>[]];
            $startTime=strtotime(($years[0]-2) . '-01-01');
            for ($i = 0; $i < 5; $i++) {
                $result['times'][] = date('Y', strtotime("+{$i} year", $startTime));
            }
            foreach ($result['times'] as $t){
                $result['achievement'][]=$achievementMoney[$t]??0;
                $result['money'][]=$list[$t]??0;
            }
        }else{
                if($status == 3){
                    $where['order_date'] = ['between', [$years[0] . '-01-01', $years[0] . '-12-31']];
                    $where['check_status'] = 2;
                    $where['owner_staff_id'] = $staff_id;
                    $moneys = Contract::where($where)->group('month')
                        ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),"%Y-%m") as month')
                        ->select();
                }else{
                    $where2['return_time'] = ['between', [$years[0] . '-01-01', $years[0] . '-12-31']];
                    $where2['check_status'] = 2;
                    $where2['owner_staff_id'] = $staff_id;
                    $moneys = Receivables::where($where2)->group('month')
                        ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),"%Y-%m") as month')
                        ->select();
                }
                $list=[];
                foreach ($moneys as $v){
                    $list[$v['month']]=$v['number'];
                }
                $achievementMoney=[];
                foreach ($achievement as $k=>$v) {
                    foreach ($v as $field => $val) {
                        $achievementMoney[$v['year'] .'-'. Achievement::getFieldMonth($field)]=$val;
                    }
                }
                $result=['times'=>[],'achievement'=>[],'money'=>[]];
                $startTime=strtotime($years[0] . '-01-01');
                for($i=0;$i<12;$i++){
                    $result['times'][]=date('Y-m',strtotime("+{$i} month",$startTime));
                }
                foreach ($result['times'] as $t){
                    $result['achievement'][]=$achievementMoney[$t]??0;
                    $result['money'][]=$list[$t]??0;
                }
        }



        $this->success('请求成功','', $result);
    }

    /**
     * 获取商机
     */
    public function get_business(){
        $times=input('times','thismonth');
        $type=input('type',2);
        if ($type == 1) {//我的
            $whereStaff['staff_id'] = $this->auth->id;
        } elseif ($type == 2) {//本人及下属
            $whereStaff['staff_id'] = ['in', Staff::getMyStaffIds()];
        } elseif ($type == 3) {//仅下属
            $whereStaff['staff_id'] = ['in', Staff::getLowerStaffId()];
        }else{
            $this->error('参数错误');
        }
        $where1=[
            'createtime'=>['between',setTimes($times,'time')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];
        $contractBusiness=Business::where($where1)->where(['status'=>'4'])->count();
        $contractBusinessMoney=Business::where($where1)->where(['status'=>'4'])->sum('money');
        $noBusiness=Business::where($where1)->where(['status'=>'5'])->count();
        $noBusinessMoney=Business::where($where1)->where(['status'=>'5'])->sum('money');
        $this->success('请求成功','',[
            'contractBusiness'=>$contractBusiness,
            'contractBusinessMoney'=>$contractBusinessMoney,
            'noBusiness'=>$noBusiness,
            'noBusinessMoney'=>$noBusinessMoney,
        ]);
    }

    /**
     * 排行
     */
    public function ranking()
    {
        //1 获客 2拜访 3业绩 4回款 5工单
        $ranking = input('ranking',1);
        $times = input('times');//2021-01,2021-07
        if (empty($times)) {
            $this->error('筛选时间不能为空');
        }
        $times = setTimes($times, 'time');
        $startTime = $times[0];
        $endTime = $times[1];
        $where = [];
        if ($ranking == 1) {//新增客户数

            $rankingList = Customer::where(['createtime' => ['between', [$startTime, $endTime]]])->where($where)
                ->with(['createStaff'])
                ->field('count(*) as number,create_staff_id')->order('number desc')->group('create_staff_id')->select();
            $rankingList = collection($rankingList)->toArray();
            $rankingList = array_slice($rankingList, 0, 10);
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
                $v['staff'] = $v['create_staff'];
                unset($v['create_staff']);
            }
        } elseif ($ranking == 2) {//新增跟进记录数

            $rankingList = Record::where(['relation_type' => 1,'follow_type'=>['neq','其它'], 'createtime' => ['between', [$startTime, $endTime]]])
                ->with(['staff'])->field('count(*) as number,create_staff_id')->order('number desc')->group('create_staff_id')->select();

            $rankingList = collection($rankingList)->toArray();
            $rankingList = array_slice($rankingList, 0, 10);
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
            }
        } elseif ($ranking == 3) {//合同金额

            $rankingList = Contract::where(['check_status' => 2, 'createtime' => ['between', [$startTime, $endTime]]])
                ->where($where)->with(['staff'])->field('sum(money) as number,owner_staff_id')->order('number desc')->group('owner_staff_id')->select();

            $rankingList = collection($rankingList)->toArray();
            $rankingList = array_slice($rankingList, 0, 10);
            $years=getYearByTime($times[0],$times[1]);
            $model = new Achievement();
            $achievement = $model->where([
                'obj_id' => $this->auth->id,
                'type' => 3,
                'year' => ['in',$years],
                'status' => 1
            ])->select();

            $achievementMoney = 0.00;
            //获取需要查询的月份
            $month = getmonthByTime($times[0],$times[1]);
            foreach ($achievement as $k=>$v) {
                foreach ($month as $key=>$val) {
                    if ($v['year'] == $key) {
                        foreach ($val as $key1=>$val1) {
                            $achievementMoney += $v[Achievement::getMonthField($v['year'].'-'.$val1)];
                        }
                    }
                }
            }
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
                $v['rate'] = $achievementMoney ? round(($v['number']/$achievementMoney),4) : 0.00;
            }
        } elseif ($ranking == 6) {//合同数

            $rankingList = Contract::where(['check_status' => 2, 'createtime' => ['between', [$startTime, $endTime]]])
                ->where($where)->with(['staff'])->field('count(*) as number,owner_staff_id')->order('number desc')->group('owner_staff_id')->select();

            $rankingList = collection($rankingList)->toArray();
            $rankingList = array_slice($rankingList, 0, 10);
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
            }
        } elseif ($ranking == 4) {//回款金额

            $rankingList = Receivables::where(['check_status' => 2, 'createtime' => ['between', [$startTime, $endTime]]])->where($where)
                ->with(['staff'])->field('count(*) as number,owner_staff_id')->order('number desc')->group('owner_staff_id')->select();

            $rankingList = collection($rankingList)->toArray();
            $rankingList = array_slice($rankingList, 0, 10);
            $years=getYearByTime($times[0],$times[1]);
            $model = new Achievement();
            $achievement = $model->where([
                'obj_id' => $this->auth->id,
                'type' => 3,
                'year' => ['in',$years],
                'status' => 2
            ])->select();

            $achievementMoney = 0.00;
            //获取需要查询的月份
            $month = getmonthByTime($times[0],$times[1]);
            foreach ($achievement as $k=>$v) {
                foreach ($month as $key=>$val) {
                    if ($v['year'] == $key) {
                        foreach ($val as $key1=>$val1) {
                            $achievementMoney += $v[Achievement::getMonthField($v['year'].'-'.$val1)];
                        }
                    }
                }
            }
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
                $v['rate'] = $achievementMoney ? round(($v['number']/$achievementMoney),4) : 0.00;
            }
        }
        $result = array("total" => count($rankingList) ,"data" => $rankingList);

        return json($result);
    }

    /**
     * 获取数据汇总
     */
    private function getCustomer(){
        $times=input('times','thismonth');
        $type=input('type',2);
        if ($type == 1) {//我的
            $whereStaff['staff_id'] = $this->auth->id;
        } elseif ($type == 2) {//本人及下属
            $whereStaff['staff_id'] = ['in', Staff::getMyStaffIds()];
        } elseif ($type == 3) {//仅下属
            $whereStaff['staff_id'] = ['in', Staff::getLowerStaffId()];
        }else{
            $this->error('参数错误');
        }
        $where1=[
            'createtime'=>['between',setTimes($times,'time')],
            'owner_staff_id'=>$whereStaff['staff_id']
        ];

        //新增客户 转成交客户 放入公海客户 公海池领取
        $addCustomer=Customer::where($where1)->count();
        $contractCustomer=Customer::where($where1)->where(['contract_status'=>1])->count();
        $seasCustomer=Customer::where(['createtime'=>$where1['createtime'],
            'create_staff_id'=>$where1['owner_staff_id']])->where(['is_seas'=>1])->count();
        $seas=Customer::where(['receivetime'=>$where1['createtime'],'owner_staff_id'=>$where1['owner_staff_id']])->count();
        //新增商机 赢单商机 输单商机 商机总金额
        $addBusiness=Business::where($where1)->count();
        $contractBusiness=Business::where($where1)->where(['status'=>'4'])->count();
        $noBusiness=Business::where($where1)->where(['status'=>'5'])->count();
        $businessMoney=Business::where($where1)->sum('money');
        //签约合同 即将到期警告 已到期 合同金额
        $addContract=Contract::where(['owner_staff_id' => $where1['owner_staff_id'],
            'order_date' => ['between', setTimes($times, 'datetime')]])->where(['check_status'=>2])->count();
        $where7day=[date('Y-m-d'), date('Y-m-d', strtotime('+7 day'))];
        $contract = Contract::where(['owner_staff_id' => $where1['owner_staff_id']])
            ->where(['end_time' => ['between',$where7day ]])
            ->where(['check_status' => 2])->count();
        $wheregtday=[date('Y-m-d', strtotime('-1 year')),date('Y-m-d')];
        $contractExpire = Contract::where(['owner_staff_id' => $where1['owner_staff_id']])
            ->where(['end_time' => ['between', $wheregtday], 'contract_status' => 0])
            ->where(['check_status' => 2])->count();
        $contractMoney=Contract::where($where1)->where(['check_status'=>2])->sum('money');
        //跟进客户数 新增待跟进客户数
        $record=Customer::where(['owner_staff_id'=>$where1['owner_staff_id'],
            'last_time'=>['between',setTimes($times,'datetime')]])->count();
        $norecord=Customer::where(['owner_staff_id'=>$where1['owner_staff_id'],
            'next_time'=>['between',setTimes($times,'datetime')]])->count();
        //回款 预计回款
        $receivables=Receivables::where(['return_time'=>['between',setTimes($times,'date')],'check_status'=>2])
            ->where(['owner_staff_id'=>$where1['owner_staff_id']])->sum('money');
        $receivablesPlan=ReceivablesPlan::where(['return_date'=>['between',setTimes($times,'date')],
            'owner_staff_id'=>$where1['owner_staff_id']])->sum('money');
        return [
            'addCustomer'=>$addCustomer,
            'contractCustomer'=>$contractCustomer,
            'seasCustomer'=>$seasCustomer,
            'seas'=>$seas,
            'addBusiness'=> $addBusiness,
            'contractBusiness'=> $contractBusiness,
            'noBusiness'=> $noBusiness,
            'businessMoney'=> $businessMoney,
            'addContract'=>$addContract,
            'contract'=> $contract,
            'contractExpire'=> $contractExpire,
            'contractMoney'=>$contractMoney,
            'record'=> $record,
            'norecord'=> $norecord,
            'receivables'=> $receivables,
            'receivablesPlan'=> $receivablesPlan,
            'where7day'=> implode(' - ',$where7day),
            'wheregtday'=> implode(' - ',$wheregtday),
        ];
    }

    /**
     * 获取值
     * @param $times
     * @param $data
     * @return array
     */
    private function getValues($times, $data)
    {
        $result = [];
        $list = [];
        foreach ($data as $v) {
            $list[$v['ctime']] = $v['c'];
        }
        $startTime = strtotime($times[1]);
        for ($i = 5; $i >= 0; $i--) {
            $date = date('Y-m', strtotime("-{$i} month",$startTime));
            $result[] = $list[$date] ?? 0;
        }
        return $result;
    }
    private function getRatio($number,$last_number){

        $last_number = $last_number ?? 0;
        if(empty($number) && empty($last_number)){
            $ratio=0;
        }elseif(empty($number) && $last_number){
            $ratio=-100;
        }elseif(empty($last_number) && $number){
            $ratio=100;
        }else{
            if($last_number > $number){
                $ratio=-(sprintf("%.2f", ($last_number-$number)/$last_number * 100));
            }else{
                $ratio=(sprintf("%.2f", ($number-$last_number)/$last_number * 100));
            }
        }
        return $ratio;
    }

}
